package com.sadam.ui4.FragmentHomePage;

import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;

import androidx.annotation.Nullable;

import com.bumptech.glide.signature.ObjectKey;
import com.sadam.ui4.Data.MySqLiteOpenHelper;
import com.sadam.ui4.Data.User;
import com.sadam.ui4.Data.Video;
import com.sadam.ui4.FragmentCommentPage.FragmentCommentPage;
import com.sadam.ui4.MainActivity;
import com.sadam.ui4.MyVideoView;
import com.sadam.ui4.R;

public class VideoViewHolder extends RecyclerView.ViewHolder {
    private ImageView ivPause;
    private TextView likeCountView;
    private TextView commentCountView;
    private TextView userNameView;
    private TextView videoTitleView;
    private MyVideoView myVideoView;
    private Button likeButton;
    private MediaPlayer mediaPlayer;
    private Video currentVideo;
    private boolean isLiked = false;
    private ImageButton userAvatarView; // 新增头像控件
    private TextView introductionView; // 新增：视频介绍
    private LinearLayout labelsLayout; // 新增：标签容器

    // 双击检测相关变量
    private long lastTapTime = 0;
    private int tapCount = 0;
    private static final int DOUBLE_TAP_TIME_DELTA = 300;
    public Button commentButton;
    private MainActivity mainActivity; // 持有主 Activity 引用

    public VideoViewHolder(@NonNull View itemView) {
        super(itemView);
        likeCountView = itemView.findViewById(R.id.texview_likecount);
        commentCountView = itemView.findViewById(R.id.textview_commentcount);
        userNameView = itemView.findViewById(R.id.textview_username);
        videoTitleView = itemView.findViewById(R.id.textview_videotitle);
        myVideoView = itemView.findViewById(R.id.myVideoView_video_recyclerview_item_layout);
        ivPause = itemView.findViewById(R.id.iv_pause);
        likeButton = itemView.findViewById(R.id.button18);
        userAvatarView = itemView.findViewById(R.id.button17); // 初始化头像控件
        commentButton = itemView.findViewById(R.id.button19); // 初始化评论按钮
        introductionView = itemView.findViewById(R.id.textview_introduction); // 初始化介绍
        labelsLayout = itemView.findViewById(R.id.layout_labels); // 初始化标签容器
        // 获取上下文并强转为 MainActivity
        if (itemView.getContext() instanceof MainActivity) {
            mainActivity = (MainActivity) itemView.getContext();
        }

        // 视频准备监听
        myVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                mediaPlayer = mp;
                mp.setLooping(true);
                mp.start();
                ivPause.setVisibility(View.GONE);
            }
        });

        // 统一的触摸监听器，处理单击（播放/暂停）和双击（点赞）
        myVideoView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (mediaPlayer == null) {return false;}

                if (event.getAction() == MotionEvent.ACTION_UP) {
                    long currentTime = System.currentTimeMillis();

                    // 双击检测
                    if (currentTime - lastTapTime < DOUBLE_TAP_TIME_DELTA) {
                        tapCount++;
                        if (tapCount == 2) {
                            // 双击点赞
                            if (currentVideo != null && !isLiked) {
                                toggleLike();
                                showLikeAnimation();
                            }
                            tapCount = 0;
                            lastTapTime = 0;
                            return true; // 消费双击事件，不触发单击
                        }
                    } else {
                        tapCount = 1;
                    }
                    lastTapTime = currentTime;

                    // 延迟执行单击处理，以等待可能的双击
                    // ✅ 定义一个 Runnable 引用，便于后续 remove
                    final Runnable clickRunnable = new Runnable() {
                        @Override
                        public void run() {
                            // 🔒 安全检查：ViewHolder 是否仍有效？MediaPlayer 是否还活着？
                            if (mediaPlayer == null) return; // ←←← 就放在这里！

                            if (System.currentTimeMillis() - lastTapTime >= DOUBLE_TAP_TIME_DELTA && tapCount == 1) {
                                try {
                                    if (mediaPlayer.isPlaying()) {
                                        mediaPlayer.pause();
                                        ivPause.setImageResource(R.drawable.ic_pause);
                                        ivPause.setVisibility(View.VISIBLE);
                                    } else {
                                        mediaPlayer.start();
                                        ivPause.setVisibility(View.GONE);
                                    }
                                } catch (IllegalStateException e) {
                                    Log.e("VideoViewHolder", "播放控制异常: ", e);
                                }
                                tapCount = 0;
                            }
                        }
                    };

                    // 先移除之前的延迟任务，避免重复执行
                    myVideoView.removeCallbacks(null); // 移除所有，或用具体引用

                    // 添加新的延迟任务
                    myVideoView.postDelayed(clickRunnable, DOUBLE_TAP_TIME_DELTA);
                }
                return true;
            }
        });

        // 点赞按钮点击事件
        likeButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (currentVideo != null) {
                    toggleLike();
                }
            }
        });
        // 设置评论按钮点击事件
        // 设置评论按钮点击事件
        commentButton.setOnClickListener(v -> {
            if (currentVideo == null) {
                Log.e("VideoViewHolder", "currentVideo is null, cannot open comment dialog");
                return;
            }

            try {
                FragmentCommentPage dialog = FragmentCommentPage.newInstance(currentVideo.getId());

                // 修复：使用正确的方式获取 Activity
                if (mainActivity != null) {
                    // 使用 mainActivity 的 SupportFragmentManager
                    dialog.show(mainActivity.getSupportFragmentManager(), "comment_dialog");
                } else {
                    // 备用方案：通过 itemView 的 Context 获取 Activity
                    if (itemView.getContext() instanceof MainActivity) {
                        MainActivity activity = (MainActivity) itemView.getContext();
                        dialog.show(activity.getSupportFragmentManager(), "comment_dialog");
                    } else {
                        Log.e("VideoViewHolder", "Cannot get MainActivity instance");
                        Toast.makeText(itemView.getContext(), "无法打开评论区", Toast.LENGTH_SHORT).show();
                    }
                }
            } catch (Exception e) {
                Log.e("VideoViewHolder", "Error opening comment dialog", e);
                Toast.makeText(itemView.getContext(), "打开评论区失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }


    private User currentUser; // 持有当前用户
    private MySqLiteOpenHelper dbHelper;

    // 修改 bind 方法
    public void bind(Video video, MySqLiteOpenHelper dbHelper, User currentUser) {
        this.currentVideo = video;
        this.dbHelper = dbHelper;
        this.currentUser = currentUser;

        // 更新 UI
        likeCountView.setText(formatCount(video.getLikeCount()));
        commentCountView.setText(formatCount(video.getCommentCount()));
        userNameView.setText(video.getUserName());
        videoTitleView.setText(video.getTitle());
        // 设置视频介绍
        if (video.getIntroduction() != null && !video.getIntroduction().isEmpty()) {
            introductionView.setText(video.getIntroduction());
            introductionView.setVisibility(View.VISIBLE);
        } else {
            introductionView.setVisibility(View.GONE);
        }

        // 设置标签
        setupLabels(video.getLabel());

        if (video.getVideoFilePath() != null && !video.getVideoFilePath().isEmpty()) {
            myVideoView.setVideoPath(video.getVideoFilePath());
        }

        myVideoView.requestFocus();

        // 加载头像
        if (video.getAvatarUrl() != null) {
            loadUserAvatar(video.getAvatarUrl());
        } else {
            setDefaultAvatar();
        }

        // 更新点赞状态
        updateLikeButtonState();
    }
    /**
     * 设置标签显示
     */
    private void setupLabels(String labelString) {
        // 清空现有标签
        labelsLayout.removeAllViews();

        if (labelString == null || labelString.trim().isEmpty()) {
            labelsLayout.setVisibility(View.GONE);
            return;
        }

        labelsLayout.setVisibility(View.VISIBLE);

//        // 分割标签字符串，如"#骑行,#城市风光,#vlog"
//        String[] tags = labelString.split(",");
        // 分割标签字符串，支持英文逗号和中文逗号
        // 例如: "#骑行,#城市风光，#vlog"
        String[] tags = labelString.split("[,，]"); // 注意：[,，] 中包含英文逗号和中文逗号

        for (String tag : tags) {
            String cleanTag = tag.trim();
            if (!cleanTag.isEmpty()) {
                // 创建标签视图
                TextView tagView = createTagView(cleanTag);
                labelsLayout.addView(tagView);
            }
        }
    }

    /**
     * 创建单个标签视图
     */
    private TextView createTagView(String tag) {
        TextView tagView = new TextView(itemView.getContext());

        // 设置标签样式
        tagView.setText(tag);
        tagView.setTextSize(10f);
        tagView.setTextColor(Color.parseColor("#E0E0E0"));
        tagView.setBackgroundResource(R.drawable.tag_background);
        tagView.setPadding(dpToPx(6), dpToPx(2), dpToPx(6), dpToPx(2));

        // 设置布局参数
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT
        );
        layoutParams.setMargins(0, 0, dpToPx(4), 0);
        tagView.setLayoutParams(layoutParams);

        return tagView;
    }

    /**
     * dp转px
     */
    private int dpToPx(int dp) {
        return (int) (dp * itemView.getContext().getResources().getDisplayMetrics().density);
    }
    /**
     * 加载用户头像
     */
    private void loadUserAvatar(String avatarUrl) {
        if (avatarUrl != null && !avatarUrl.isEmpty()) {
            loadAvatarWithGlide(avatarUrl);
        } else {
            // 设置默认头像
            setDefaultAvatar();
        }
    }

    /**
     * 使用 Glide 加载头像（推荐方式）
     */
    private void loadAvatarWithGlide(String avatarUrl) {
        Glide.with(itemView.getContext())
                .load(avatarUrl)
                .signature(new ObjectKey(System.currentTimeMillis() / (1 * 1000))) // 每10秒刷新缓存
                .placeholder(R.drawable.shape_round)
                .error(R.drawable.shape_round)
                .apply(RequestOptions.circleCropTransform())
                .into(new SimpleTarget<Drawable>() {
                    @Override
                    public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                        userAvatarView.setBackground(resource);
                    }
                });
    }
    /**
     * 设置默认头像
     */
    private void setDefaultAvatar() {
        userAvatarView.setBackgroundResource(R.drawable.shape_round);
    }
    private void toggleLike() {
        if (currentUser == null) {
            Toast.makeText(itemView.getContext(), "请先登录", Toast.LENGTH_SHORT).show();
            return;
        }

        long videoId = currentVideo.getId();
        long userId = currentUser.getId();

        boolean isNowLiked = dbHelper.toggleLike(videoId, userId);
        isLiked = isNowLiked;

        // 更新 UI
        likeButton.setBackgroundResource(isLiked ? R.drawable.btn_like_selected : R.drawable.btn_like);

        int currentCount = Integer.parseInt(likeCountView.getText().toString().replaceAll("[KkWw]", ""));
        likeCountView.setText(formatCount(isLiked ? currentCount + 1 : currentCount - 1));

        showLikeAnimation();
        Toast.makeText(itemView.getContext(), isLiked ? "已点赞" : "取消点赞", Toast.LENGTH_SHORT).show();

        // ✅ 新增：通知作品列表刷新数据
        notifyCompositionFragmentRefresh();
    }

    // ✅ 新增方法：通知作品列表刷新
    private void notifyCompositionFragmentRefresh() {
        if (mainActivity != null) {
            // 通过 MainActivity 刷新作品列表
            mainActivity.refreshFragmentComposition();
        }
    }
    private void updateLikeButtonState() {
        if (currentUser == null) {
            isLiked = false;
            likeButton.setBackgroundResource(R.drawable.btn_like);
            return;
        }

        isLiked = dbHelper.hasLiked(currentVideo.getId(), currentUser.getId());
        likeButton.setBackgroundResource(isLiked ? R.drawable.btn_like_selected : R.drawable.btn_like);
    }

    private void showLikeAnimation() {
        // 这里可以添加点赞动画效果
        // 例如显示一个心形动画
        likeButton.animate()
                .scaleX(1.2f)
                .scaleY(1.2f)
                .setDuration(200)
                .withEndAction(() -> likeButton.animate()
                        .scaleX(1.0f)
                        .scaleY(1.0f)
                        .setDuration(200)
                        .start())
                .start();
    }

    private String formatCount(int count) {
        if (count < 1000) {
            return String.valueOf(count);
        } else if (count < 10000) {
            return String.format("%.1fK", count / 1000.0);
        } else {
            return String.format("%.1fW", count / 10000.0);
        }
    }

    public void pause() {
        if (mediaPlayer != null) {
            try {
                if (mediaPlayer.isPlaying()) {
                    mediaPlayer.pause();
                }
            } catch (IllegalStateException e) {
                // 记录日志，避免崩溃
                Log.e("VideoViewHolder", "MediaPlayer in illegal state when calling isPlaying()", e);
            }
        }
    }
    public void resume() {
        if (mediaPlayer != null && !mediaPlayer.isPlaying()) {
            try {
                mediaPlayer.start();
                ivPause.setVisibility(View.GONE);
            } catch (Exception e) {
                Log.e("VideoViewHolder", "恢复播放失败", e);
            }
        } else if (mediaPlayer == null && currentVideo != null) {
            // MediaPlayer 被释放了，重新设置路径并播放
            myVideoView.setVideoPath(currentVideo.getVideoFilePath());
            ivPause.setVisibility(View.GONE);
            Log.d("VideoViewHolder", "MediaPlayer 已释放，重新设置路径并播放");
        } else {
            Log.w("VideoViewHolder", "Media player 为空或正在播放");
        }
    }

    public void release() {
        if (mediaPlayer != null) {
            try {
                mediaPlayer.release(); // 释放原生资源
            } catch (Exception e) {
                Log.e("VideoViewHolder", "Error releasing MediaPlayer", e);
            } finally {
                mediaPlayer = null;
            }
        }
    }
}